package config;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.log4j.Logger;

public class DatabaseConnection
{
    private static Logger myLogger = Logger.getLogger(DatabaseConnection.class.getName()); 

    
    
    /**
     * Connections to the database
     * 
     * @return
     */
    public static Connection startDBConnection()
    {
	Connection dbConnection = null;
	try
	{
	    Class.forName("com.mysql.jdbc.Driver").newInstance();
	}
	catch (InstantiationException | IllegalAccessException
		| ClassNotFoundException e1)
	{
	    myLogger.error("Could not connect to the database.", e1);
	    return dbConnection;
	}
	String dbURL = "jdbc:mysql://" + ConfigData.dbHost+"/"+ConfigData.dbName;
	myLogger.info("Attemping to connect to the database with information: " + dbURL + " - " + ConfigData.dbUserName + " - " + ConfigData.dbPassword);
	try
	{
	    dbConnection = DriverManager.getConnection(dbURL, ConfigData.dbUserName, ConfigData.dbPassword);
	    myLogger.info("Connected to the database.");
	}
	catch (SQLException e)
	{
	    myLogger.error("Could not connect to the database", e);
	    return dbConnection;
	}
	
	return dbConnection;
    }
    
    /**
     * Closes connection to the database.
     * @return success
     */
    public static boolean closeConnection(Connection dbConnection)
    {
	try
	{
	    dbConnection.close();
	    myLogger.info("Closed connection to the database.");
	    return true;
	}
	catch (SQLException e)
	{
	    myLogger.error("Could not close connection to the database", e);
	    return false;
	}
    }
    
    public static boolean executeQuery(String query, String tableName)
    {
	// Add to the database
	Statement statement;
	Connection dbc = null;
	try
	{
	    myLogger.info("Attempting to save to " + tableName + " in the database.");
	    dbc = DatabaseConnection.startDBConnection();
	    statement = dbc.createStatement();
	    myLogger.info("Executing query: " + query);
	    statement.executeUpdate(query);
	    myLogger.info("Successfully saved this " + tableName + " in the database.");
	    return true;
	}
	catch (SQLException e)
	{
	    myLogger.error("Could not add this " + tableName + " in the database.");
	    return false;
	}
	finally
	{
	    if (null != dbc)
	    {
		DatabaseConnection.closeConnection(dbc);
	    }
	}
    }
}
